package org.zhb.sys.shiro.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.zhb.sys.shiro.user.repository.UserRepository;
import org.zhb.sys.shiro.user.service.UserService;

import org.zhb.sys.shiro.model.User;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	UserRepository userRepository;

	@Override
	public User selectByUserName(String userName) {
		return userRepository.findByUserName(userName);
	}

	@Override
	public User insert(User user) {
		return userRepository.saveAndFlush(user);
	}

	@Override
	public User selectUserById(String id) {
		return userRepository.findOne(id);
	}

	@Override
	public User update(User user) {
		return userRepository.saveAndFlush(user);
	}

	@Override
	public void delete(String id) {
		userRepository.delete(id);
	}

	@Override
	public void saveBatch(List<User> users) {
		userRepository.save(users);
	}

	@Override
	public Page<User> selectModelByCondition(User user, PageRequest pageRequest) {
		Specification<User> specification = getWhereClause(user);
		Page<User> userList = userRepository.findAll(specification, pageRequest);
		return userList;
	}

	/**
	 * 条件拼接
	 * 
	 * @param user
	 * @return
	 */
	private Specification<User> getWhereClause(User user) {
		// Lambda表达式
		Specification<User> specification = (root, query, cb) -> {
			List<Predicate> predicate = new ArrayList<>();
			if (StringUtils.isNotEmpty(user.getUserName())) {
				predicate.add(cb.like(root.get("userName").as(String.class), "%" + user.getUserName()));
			}
			Predicate[] pre = new Predicate[predicate.size()];
			return query.where(predicate.toArray(pre)).getRestriction();
		};
		return specification;
	}

	@Override
	public Page<User> selectModelByCondition(PageRequest pageRequest) {
		return userRepository.findAll(pageRequest);
	}

	@Override
	public void updatePasswordByUserName(String password, String userName) {
		userRepository.updatePasswordByUserName(password, userName);
	}

	@Override
	public User findByPhone(String phone) {
		return userRepository.findByPhone(phone);
	}

	@Override
	public User findByEmail(String email) {
		return userRepository.findByEmail(email);
	}

	@Override
	public List<User> selectAllUser() {
		return userRepository.findAll();
	}
}
